package com.mystudy.dataStructure.tree;

import com.mystudy.dataStructure.queue.LinkedListQueue;
import com.mystudy.dataStructure.queue.Queue;
import com.mystudy.dataStructure.stack.ArrayStack;
import com.mystudy.dataStructure.stack.Stack;

/**
 * @program: infoalgorithm
 * @description: 二分搜索树
 * @author: zhouzhilong
 * @create: 2019-07-12 17:23
 **/
public class BST<E extends Comparable> {
    private Node root;
    private int size;

    public BST() {
        root = null;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 向树中添加新的元素
     *
     * @param e
     */
    public void add(E e) {
        root = add(root, e);
    }

    /**
     * 想以node为根的二分搜索树中插入元素E，递归算法
     *
     * @param node
     * @param e
     * @return 返回插入新节点后二分搜索的根
     */
    private Node add(Node node, E e) {
        //终止条件
        if (node == null) {
            size++;
            return new Node(e);
        }
        if (e.compareTo(node.e) < 0) {
            node.left = add(node.left, e);
        } else {
            node.right = add(node.right, e);
        }
        return node;
    }


    public boolean contains(E e) {
        return contains(root, e);
    }

    /**
     * 以node为根的二分搜索树是否包含元素e，递归算法
     *
     * @param node
     * @param e
     * @return
     */
    private boolean contains(Node node, E e) {
        if (node == null) {
            return false;
        }

        if (e.compareTo(node.e) == 0) {
            return true;
        } else if (e.compareTo(node.e) < 0) {
            return contains(node.left, e);
        } else {
            return contains(node.right, e);
        }

    }


    /**
     * 二分搜索树的前序遍历
     */
    public void preOrder() {
        preOrder(root);
    }

    /**
     * 前序遍历以node为根的二分搜索树，递归算法
     *
     * @param node
     */
    private void preOrder(Node node) {
        if (node == null) {
            return;
        }
        System.out.println(node.e);
        preOrder(node.left);
        preOrder(node.right);

    }


    /**
     * 中序遍历
     */
    public void inOrder() {
        inOrder(root);
    }

    /**
     * 中序遍历以node为根的二分搜索树，递归算法
     *
     * @param node
     */
    private void inOrder(Node node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        System.out.println(node.e);
        inOrder(node.right);
    }


    /**
     * 后序遍历
     */
    public void postOrder() {
        postOrder(root);
    }

    /**
     * 后序遍历以node为根的二分搜索树，递归算法
     *
     * @param node
     */
    private void postOrder(Node node) {
        if (node == null) {
            return;
        }
        postOrder(node.left);
        postOrder(node.right);
        System.out.println(node.e);
    }


    /**
     * 二分搜索树的非递归算法
     */
    public void preOrderNR() {
        Stack<Node> stack = new ArrayStack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node cur = stack.pop();
            System.out.println(cur.e);
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
        }
    }

    /**
     * 广度优先遍历，或者说层序遍历
     */
    public void levelOrder() {
        Queue<Node> queue = new LinkedListQueue<>();
        queue.enqueue(root);
        while (!queue.isEmpty()) {
            Node cur = queue.dequeue();
            System.out.println(cur.e);
            if (cur.left != null) {
                queue.enqueue(cur.left);
            }
            if (cur.right != null) {
                queue.enqueue(cur.right);
            }
        }
    }

    /**
     * 深度优先遍历
     */
    public void depthOrder(){
        Stack<Node> stack = new ArrayStack();
        stack.push(root);
        while(!stack.isEmpty()){
            Node cur = stack.pop();
            System.out.println(cur.e);
            if(cur.right!= null){
                stack.push(cur.right);
            }
            if(cur.left != null){
                stack.push(cur.left);
            }
        }
    }





    /**
     * 寻找二分搜素树的最小元素
     * @return
     */
    public E mimiMum(){
        if(size == 0){
            throw new IllegalArgumentException("BST is empty");
        }
        return miniMum(root).e;
    }
    private Node miniMum(Node node){
        if(node.left == null){
            return node;
        }else{
            return miniMum(node.left);
        }
    }

    /**
     * 寻找二分搜索树的最大元素
     * @return
     */
    public E maxMum(){
        if(size == 0){
            throw new IllegalArgumentException("BST is empty");
        }
        return maxMum(root).e;
    }

    private Node maxMum(Node node){
        if(node.right == null){
            return node;
        }else{
            return miniMum(node.right);
        }
    }


    public E removeMin(){
        //获取要删除的节点
        E e = mimiMum();
        root = removeMin(root);
        return e;
    }

    /**
     * 删除掉以node为根的二分搜索树中的最小节点
     * 返回删除节点后的新的二分搜索树的根
     * @param node
     * @return
     */
    private Node removeMin(Node node){
        if(node.left == null){
            Node rightNode =  node.right;
            node.right = null;//解除内存占用
            size--;
            return rightNode;
        }else{
            node.left = removeMin(node.left);
            return node;
        }
    }


    public E removeMax(){
        //获取要删除的节点
        E e = maxMum();
        root = removeMax(root);
        return e;
    }

    /**
     * 删除掉以node为根的二分搜索树中的最大节点
     * 返回删除节点后的新的二分搜索树的根
     * @param node
     * @return
     */
    private Node removeMax(Node node){
        if(node.right == null){
            Node leftNode =  node.left;
            node.left = null;//解除内存占用
            size--;
            return leftNode;
        }else{
            node.right = removeMax(node.right);
            return node;
        }
    }

    /**
     * 从二分搜索数中删除元素为e的点
     * @param e
     */
    public void remove(E e){
        root = remove(root,e);
    }
    private Node remove(Node node,E e){
        if(node == null){
            return null;
        }
        if(e.compareTo(node.e)<0){
            node.left = remove(node.left,e);
            return node;
        }else if(e.compareTo(node.e)>0){
            node.right = remove(node.right,e);
            return node;
        }else{
            //说面当前e＝＝node.e，稍微复杂
            if(node.left == null){
                Node rightNode =  node.right;
                node.right = null;//解除内存占用
                size--;
                return rightNode;
            }

            if(node.right == null){
                Node leftNode =  node.left;
                node.left = null;//解除内存占用
                size--;
                return leftNode;
            }

            //最复杂的情况，左子树与右子树都不为空,要找到合适的替代的节点
            //找到比要删除的节点大的最小节点，也就是要删除节点的右子树的最小节点
            Node successor = miniMum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;
            node.left = node.right =null;//解除内存占用
            return successor;
        }
    }





    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        generateBSTString(root, 0, result);
        return result.toString();
    }

    /**
     * 生成以node为根节点，深度为depth的描述二叉树的字符串
     *
     * @param node   要遍历的根节点
     * @param depth  该根节点所在深度
     * @param result 最终生成的结果
     */
    private void generateBSTString(Node node, int depth, StringBuilder result) {
        if (node == null) {
            result.append(generateDepthString(depth) + "null\n");
            return;
        }
        result.append(generateDepthString(depth) + node.e + "\n");
        generateBSTString(node.left, depth + 1, result);
        generateBSTString(node.right, depth + 1, result);

    }

    private String generateDepthString(int depth) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            res.append("--");
        }
        return res.toString();
    }

    public Node getRoot() {
        return root;
    }

    public class Node {
        public E e;
        public Node left;
        public Node right;


        public Node(E e) {
            this.e = e;
        }
    }

}
